import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { postLogin, postLogout } from '../services/login';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';
import { hex_md5 } from '@/utils/md5';
import { message } from 'antd';
import recode from '@/utils/recode'
import Cookies from 'universal-cookie';
const cookie = new Cookies();


export default {
  namespace: 'login',

  state: {
    type: 'login',
    status: undefined,
    pwd: '',
    loading: false,
    token:'',
    account: '',

    userId: '',
    currentUser:{}
  },

  effects: {
    *login({ payload, history }, { call, put }) {
      var ip = returnCitySN.cip;
      var params = {
        account : payload.account,
        pwd : hex_md5(payload.pwd),
        ip : ip
      };
      const data = yield call(postLogin, params);

      console.log("===",data.body);
      if(!data.body.userId){
        return;
      }
      // if (recode(data)){
      //   return;
      // }
      cookie.set("name", params.account, { path: '/' });
      cookie.set("userId", data.body.userId, { path: '/' });
      cookie.set("role", data.body.roles, { path: '/' });
      let array = data.body.permissions;
      array.push('/admin/login');
      yield put({
        type: 'changeLoginStatus',
        payload: {
          userId: data.body.userId,
          status: true,
          currentAuthority: array,
        },
      });
      reloadAuthorized();
      yield put(routerRedux.push('/'));
    },
    *logout({payload}, { call, put, select }) {
      const data = yield call(postLogout, payload);
      //console.log(data);
      if (data){
        if (data.recode == 200){
          yield put({
            type: 'changeLoginStatus',
            payload: {
              status: false,
              currentAuthority: 'guest'
            }
          });
          reloadAuthorized();
          cookie.remove("userId", { path: '/' });
          cookie.remove("name", { path: '/' });
          cookie.remove("role", { path: '/' });
          yield put(routerRedux.push('/user/login'));
        } else {
          // message.error('网络请求失败');
        }
      } else {
        // message.error('网络请求失败');
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      return {
        ...state,
        status: payload.status,
        type: payload.type,
      };
    },
  },
};
